package org.example.road.learn01.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.example.road.learn01.OutMemoryError2;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Slf4j
public class PingHandler extends ChannelInboundHandlerAdapter {

    private static final String pingCon = "PING Server";

    private Integer idleTime = 0;

    public PingHandler(int idleTime) {
        this.idleTime = idleTime;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 5秒中发生一次心跳
        Runnable task = new Runnable() {
            @Override
            public void run() {
                ByteBuf buf = Unpooled.copiedBuffer(pingCon.getBytes(StandardCharsets.UTF_8));
                final Integer clientId = ctx.channel().attr(OutMemoryError2.idAttr).get();
                if (ctx.channel().isActive() && ctx.channel().isWritable()) {
                    log.info("连接{}发送心跳", clientId);
                    ctx.channel().writeAndFlush(buf);
                    ctx.executor().schedule(this, idleTime, TimeUnit.SECONDS);
                }
            }
        };
        ctx.executor().schedule(task, idleTime, TimeUnit.SECONDS);
    }
}
